package org.lc.stk.service;

import java.util.List;
import java.util.stream.Collectors;

import org.lc.stk.model.User;
import org.lc.stk.repository.UserRepository;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("正在查询用户: " + username);
        
        User user = userRepository.findByUsername(username)
            .orElseThrow(() -> {
                System.out.println("用户未找到: " + username);
                return new UsernameNotFoundException("用户不存在: " + username);
            });

        System.out.println("找到用户: " + user.getUsername());
        System.out.println("数据库中的密码哈希: " + user.getPassword());
        
        List<SimpleGrantedAuthority> authorities = user.getRoles().stream()
            .map(role -> {
                String roleWithPrefix = "ROLE_" + role.getName();
                System.out.println("添加权限: " + roleWithPrefix);
                return new SimpleGrantedAuthority(roleWithPrefix);
            })
            .collect(Collectors.toList());

        UserDetails userDetails = new org.springframework.security.core.userdetails.User(
            user.getUsername(),
            user.getPassword(),
            authorities
        );

        System.out.println("创建UserDetails完成，用户名: " + userDetails.getUsername());
        System.out.println("UserDetails中的权限: " + userDetails.getAuthorities());
        
        return userDetails;
    }
}